<?php

namespace app\yperp\common;

use app\admin\model\Attachment;
use think\Image;

class Tools
{
    static function jsonImageToView($value)
    {
        $images =  json_decode($value, true);
        $imgs = '<div class="js-gallery">';
        foreach ($images as $key => $image) {
            $imgs .= ' <img class="image" data-original="' . $image . '" src="' . $image . '">';
        }
        $imgs .= '</div>';
        return $imgs;
    }

    static public function saveZipFileToGoodsPath($goods_imgs_file = null)
    {

        $file_path =  env('root_path') . 'public' . DIRECTORY_SEPARATOR .  get_file_path($goods_imgs_file);

        $goods_code = get_file_name($goods_imgs_file);

        // 删除文件后缀名（假设后缀名是以点号开头，后跟一个或多个字母）
        $goods_code = preg_replace('/\.\w+$/', '', $goods_code);

        $goods_code = Pinyin('permalink', $goods_code, '_');

        $extractToDir = env('root_path') . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'goods' . DIRECTORY_SEPARATOR . $goods_code;

        isdir($extractToDir);

        // 打开 ZIP 文件
        $zipFile = new \PhpZip\ZipFile();
        $zipFile->openFile($file_path); // open archive from file

        $listFiles = $zipFile->getListFiles();
        $zip_one_dir =    explode('/', $listFiles[0])[0];

        $zipFile->extractTo($extractToDir); // extract files to the specified directory
        $zipFile->close();;

        moveFilesToDirectory($extractToDir . DIRECTORY_SEPARATOR . $zip_one_dir, $extractToDir);
        rmdir($extractToDir . DIRECTORY_SEPARATOR . $zip_one_dir);

        // 遍历数组中的每个文件名
        $excelFiles = '';
        foreach ($listFiles as $file) {
            // 使用字符串函数检查文件扩展名
            if (strpos($file, '.xls') !== false || strpos($file, '.xlsx') !== false) {
                // 如果文件名包含 .xls 或 .xlsx，则添加到结果数组中
                $excelFiles = $extractToDir . DIRECTORY_SEPARATOR . $file;
            }
        }

        $excelFiles = str_replace(DIRECTORY_SEPARATOR . $zip_one_dir, '', $excelFiles);

        return [$excelFiles, $goods_code];
    }

    /**
     * 创建缩略图
     * @param string $file 目标文件，可以是文件对象或文件路径
     * @param string $dir 保存目录，即目标文件所在的目录名
     * @param string $save_name 缩略图名
     * @param string $thumb_size 尺寸
     * @param string $thumb_type 裁剪类型
     * @author 蔡伟明 <314013107@qq.com>
     * @return string 缩略图路径
     */
    static function create_thumb($file = '', $dir = '', $save_name = '', $thumb_size = '', $thumb_type = '')
    {
        // 获取要生成的缩略图最大宽度和高度
        $thumb_size = $thumb_size == '' ? config('upload_image_thumb') : $thumb_size;
        dump(config('upload_image_thumb'));
        dump($thumb_size);
        list($thumb_max_width, $thumb_max_height) = explode(',', $thumb_size);
        // 读取图片
        $image = Image::open($file);
        // 生成缩略图
        $thumb_type = $thumb_type == '' ? config('upload_image_thumb_type') : $thumb_type;
        $image->thumb($thumb_max_width, $thumb_max_height, $thumb_type);
        // 保存缩略图
        $thumb_path = config('upload_path') . DIRECTORY_SEPARATOR . 'images/' . $dir . '/thumb/';
        if (!is_dir($thumb_path)) {
            mkdir($thumb_path, 0766, true);
        }
        $thumb_path_name = $thumb_path . $save_name;
        $image->save($thumb_path_name);
        $thumb_path_name = 'uploads/images/' . $dir . '/thumb/' . $save_name;
        return $thumb_path_name;
    }
    static function downImage($url = '')
    {
        // 检查输入参数是否为空
        if (empty($url)) {
            return false;
        }

        $url_sha1 = sha1($url);
        $FileInfo =  Attachment::where('sha1', $url_sha1)->find();
        if (!$FileInfo) {

            // 初始化cURL会话
            $ch = curl_init();

            // 设置cURL选项以支持HTTPS请求和获取内容
            curl_setopt($ch, CURLOPT_URL, $url);          // 可以是HTTP或HTTPS图片URL
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_FAILONERROR, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 允许重定向
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁止cURL验证SSL证书（仅开发环境使用，生产环境中应开启并验证证书）
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 同上，开发环境可以暂时关闭，生产环境请设置为2并确保正确配置了CA证书

            // 执行cURL请求
            $image_content = curl_exec($ch);

            // 检查cURL请求是否成功
            if (curl_errno($ch)) {
                echo 'Curl error: ' . curl_error($ch);
                curl_close($ch);
                return false;
            }

            // 获取HTTP响应码
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($http_code !== 200) {
                echo "HTTP request failed with code $http_code";
                curl_close($ch);
                return false;
            }

            // 关闭cURL会话
            curl_close($ch);

            $dir_name = date('Ymd');
            $file_dir = config('upload_path') . DIRECTORY_SEPARATOR . 'images/' . $dir_name . DIRECTORY_SEPARATOR;
            if (!is_dir($file_dir)) {
                mkdir($file_dir, 0766, true);
            }

            $parts = explode('?', $url);

            // 返回不包含查询字符串的第一部分
            $url =  isset($parts[0]) ? $parts[0] : '';
            $EXTENSION = '';
            try {
                $EXTENSION =  pathinfo($url, PATHINFO_EXTENSION);
            } catch (\Throwable $th) {
                $EXTENSION =  'jpg';
            }
            $new_file = $file_dir . $url_sha1 . '.' . $EXTENSION;

            // 将图片内容写入文件
            $fp = fopen($new_file, 'w');
            fwrite($fp, $image_content);
            fclose($fp);

            // 检查文件是否已成功保存到指定路径
            if (!file_exists($new_file)) {
                return false;
            }

            // 生成缩略图
            $thumb_path_name = '';
            // if (config('upload_image_thumb') != '') {
            // $thumb_path_name = self::create_thumb($new_file, $url_sha1, md5($new_file));
            // }

            // 获取附件信息
            $file_info = [
                'uid' => session('user_auth.uid'),
                'name' => pathinfo($new_file, PATHINFO_FILENAME),
                'mime' => mime_content_type($new_file),
                'path' =>  str_replace('\\', '/', str_replace(env('root_path') . 'public\\', '', $new_file)),
                'ext' => pathinfo($new_file, PATHINFO_EXTENSION),
                'size' => filesize($new_file),
                'md5' => md5_file($new_file),
                'sha1' => $url_sha1,
                'thumb' => $thumb_path_name,
                'module' => 'yperp',
                'width' => getimagesize($new_file)[0],
                'height' => getimagesize($new_file)[1],
            ];
            // dump($file_info);
            Attachment::create($file_info);
            return Attachment::where('sha1', $url_sha1)->find();
        } else {
            return  $FileInfo;
        }
    }
    static function ypapp($data, $token)
    {
        try {
            $n['body'] = $data;
            $h = 'token';
            if ($h) {
                $n['headers']['token'] = $token;
                $n['headers']['timestamp'] = (string)time();
            }

            $f = array_keys($n['body']);
            sort($f);
            $d = '';
            foreach ($f as $p => $key) {
                $g = $n['body'][$key];
                if ((is_bool($g) || !empty($g)) && is_object($g)) {
                    $g = json_encode($g);
                }
                if (!empty($g)) {
                    $d .= "{$key}={$g}&";
                }
            }
            $v = rtrim($d, '&');
            if (!empty($v)) {
                $v .= '&';
            }

            $m = $v . "key=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIcw1D6Cc3wACTxg/haj2VxyO3nhQ2l64xZXHdNbUdfghx9o+A04576853F6BE280C5ADE36F91102ECC/IljhSLrJAiqfBuh2UCAwEAAQ==";
            $y = strtoupper(md5($m));
            if (!empty($y)) {
                $n['headers']['sign'] = $y;
            }
            return $n;
        } catch (\Throwable $th) {
            //throw $th;
            var_dump($th->getMessage());
            var_dump($th->getTraceAsString());
        }
    }
}
